﻿using MediaToolkit;
using MediaToolkit.Model;
using MediaToolkit.Options;
using System;
using System.Collections.Generic;
using System.IO;
using Wallpaper.Partial;

namespace Wallpaper.Class
{
    public static class Files
    {
        public const string VideoFileDir = @"source";
        public const string SettingFileName = @"setting.wp";

        /// <summary>
        /// 更新动态壁纸列表
        /// </summary>
        /// <returns></returns>
        public static List<ItemUnit> GetVideoList()
        {
            List<ItemUnit> units = new List<ItemUnit>();
            string[] infos = Directory.GetDirectories(VideoFileDir);
            foreach (string dir in infos)
            {
                try
                {
                    units.Add(GetItemUnit(dir));
                }
                catch (Exception e) 
                {
                    Dialog.ShowDialog_Exception(e);
                }
            }
            return units;
        }

        public static ItemUnit GetItemUnit(string dir)
        {
            string settingFile = Path.Combine(dir, SettingFileName);
            ItemUnitBased unit = ItemUnitBased.ReadFromFile(settingFile);
            return new ItemUnit(unit);
        }

        /// <summary>
        /// 从已存在的视频里导入动态壁纸,如果成功则返回路径
        /// </summary>
        /// <param name="filepath">视频路径</param>
        public static string ImportVideoFromDevice(string filepath, string title = null, string cover = null)
        {
            try
            {
                string dirname = GetRandomName();
                while (Directory.Exists(Path.Combine(VideoFileDir, dirname)))
                {
                    dirname = GetRandomName();
                }
                string targetDir = Path.Combine(VideoFileDir, dirname); // 目标文件夹
                string targetName = Path.GetFileName(filepath); // 目标文件名
                string targetCover = Path.Combine(targetDir, "cover.jpg"); // 目标封面图
                //防止和配置文件重名
                if (targetName == SettingFileName)
                {
                    targetName = targetName + "1";
                }
                string targetFullPath = Path.Combine(targetDir, targetName); // 目标文件完整路径
                //复制文件
                Directory.CreateDirectory(targetDir);
                File.Copy(filepath, Path.Combine(targetDir, targetName), true);
                //生成封面图
                if(cover == null)
                {
                    MediaFile source = new MediaFile() { Filename = filepath };
                    MediaFile aim = new MediaFile() { Filename = targetCover };
                    ConversionOptions options = new ConversionOptions() { Seek = TimeSpan.Zero };
                    Engine engine = new Engine();
                    engine.GetThumbnail(source, aim, options);
                }
                else
                {
                    File.Copy(cover, targetCover);
                }
                //创建ItemUnitBased对象
                if (title == null)
                {
                    title = Path.GetFileNameWithoutExtension(filepath);
                }
                ItemUnitBased unit = new ItemUnitBased()
                {
                    VideoTitle = title,
                    VideoPath = targetFullPath,
                    ImagePath = targetCover
                };
                //写入配置文件
                unit.WriteToFile(Path.Combine(targetDir, SettingFileName));
                return targetDir;
            }
            catch(Exception e)
            {
                Dialog.ShowDialog_Exception(e);
                return null;
            }

            string GetRandomName()
            {
                const int RandomDirNameMinLength = 6; // 最小值6
                const int RandomDirNameMaxLength = 11; // 最大值10 (+1)
                Random random = new Random();
                int DirNameLength = random.Next(RandomDirNameMinLength, RandomDirNameMaxLength);
                string name = "";
                for (int i = 0; i < DirNameLength; i++)
                {
                    name += random.Next(10);
                }
                return name;
            }
        }

        public static void Init()
        {
            if (!Directory.Exists(VideoFileDir))
            {
                Directory.CreateDirectory(VideoFileDir);
            }
            
        }

        /// <summary>
        /// 从文件中读取设置
        /// </summary>
        /// <returns></returns>
        public static WallpaperSetting ReadWallpaperSetting()
        {
            if (File.Exists(SettingFileName))
            {
                try
                {
                    return WallpaperSetting.ReadFromFile(SettingFileName);
                }
                catch (Exception) { }
            }
            return new WallpaperSetting();
        }

        public static void SaveSetting()
        {
            Static.wallpaperSetting.WriteToFile(SettingFileName);
        }
    }
}
